/*



 */
package com.bbh.plugin.single.privilege.demo.controller;


import com.bbh.plugin.single.privilege.core.entity.App;
import com.bbh.plugin.single.privilege.core.entity.Role;
import com.bbh.plugin.single.privilege.core.entity.RoleRule;
import com.bbh.plugin.single.privilege.core.enums.BaseEnum;

import com.bbh.common.base.vo.GridVo;
import com.bbh.plugin.single.privilege.core.service.AppService;
import com.bbh.plugin.single.privilege.core.service.RoleRuleService;
import com.bbh.plugin.single.privilege.core.service.RoleService;
import com.bbh.plugin.single.privilege.core.service.RuleService;
import com.bbh.plugin.single.privilege.core.vo.tree.RuleVo;
import com.bbh.common.domain.Condition;
import com.bbh.common.domain.Message;
import com.bbh.common.domain.StatusType;
import com.bbh.common.utils.IdUtils64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.bbh.common.domain.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Controller - 角色
 *
 * @author KCSHOP Team
 * @version 3.0
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BasicController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRuleService roleRuleService;
    @Autowired
    private RuleService ruleService;
    @Autowired
    private AppService appService;
    @Value("${system.appKey}")
    private String systemAppKey;

    /**
     * 跳转角色首页
     *
     * @author bestgwd
     */
    @RequestMapping(value = VIEW_FILED + "/index", method = RequestMethod.GET)
    public String toResourceIndex(ModelMap model) {
        model.addAttribute("statusItems", EnumSet.allOf(BaseEnum.IS_ENABLED.class));
        return "single/role/index";
    }

    /**
     * 跳转资源增加页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = INSERT_FILED + "/toAdd", method = RequestMethod.GET)
    public String toAddResource(ModelMap model) {

        model.addAttribute(OPERATE_TYPE, "add");
        return "single/role/edit";
    }

    /**
     * 增加角色
     *
     * @param role
     * @return
     */
    @RequestMapping(value = INSERT_FILED + "/insert", method = RequestMethod.POST)
    @ResponseBody
    public Message insert(@Validated Role role) {
        Condition condition = new Condition();
        if (StringUtils.isNotBlank(role.getEnname())) {
            condition.putEquals("enname", role.getEnname());
        }
        if (!roleService.existsCheckEach(condition)) {
            Date date = new Date();
            role.setCreateTime(date);
            role.setModifyTime(date);
            role.setCreateBy(getPrincipal().getLoginName());
            role.setModifyBy(getPrincipal().getLoginName());
            role.setId(IdUtils64.getInstance().getStringId());
            role.setDataStatus(BaseEnum.DATA_STATUS.NORMAL.getKey());
            role.setIsSys("1");
            role.setAppKey(systemAppKey);
            roleService.insert(role);
            return new Message(StatusType.SUCCESS.getKey(), "增加成功");
        }
        return new Message(StatusType.WARN.getKey(), "英文名已存在，不能重复增加");
    }

    /**
     * 角色列表
     *
     * @param request
     * @param model
     * @param name
     * @param
     * @return
     * @throws ServletRequestBindingException
     */
    @RequestMapping(value = VIEW_FILED + "/list")
    @ResponseBody
    public GridVo list(HttpServletRequest request, Model model, String name, String isEnabled) throws ServletRequestBindingException {
        Condition params = new Condition();
        if (StringUtils.isNoneBlank(name)) {
            params.put("LIKE_name", name);
        }
        params.put("EQ_dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        if (StringUtils.isNoneBlank(isEnabled)) {
            params.put("EQ_isEnabled", isEnabled);
        }
        GridVo vo = new GridVo();
        Page<Role> pageResult = roleService.selectPage(params, null, initPageRequest(request, PAGE_NUMBER, PAGE_ROWS));

        return new GridVo(pageResult);
    }

    /**
     * 跳转到edit页面
     *
     * @return
     */
    @RequestMapping(value = UPDATE_FILED + "/toEdit", method = RequestMethod.GET)
    public String edit(String id, Model model) {
        Role role = roleService.selectByPrimaryKey(id);
        App app = appService.findByAppNameCode(role.getAppKey());
        model.addAttribute("role", role);
        model.addAttribute(OPERATE_TYPE, "edit");
        model.addAttribute("app", app);
        return "single/role/edit";
    }

    /**
     * 更新角色
     * update
     *
     * @return
     */
    @RequestMapping(value = UPDATE_FILED + "/update", method = RequestMethod.POST)
    @ResponseBody
    public Message update(Role role, String checks) {
        String loginName = getLoginName();
        int cont = roleService.updateRoleSource(role, checks, loginName);
        if (cont == 0) {
            return new Message(StatusType.WARN.getKey(), "参数错误");
        } else if (cont == 2) {
            return new Message(StatusType.WARN.getKey(), "英文名已存在，不能重复增加");
        }
        return new Message(StatusType.SUCCESS.getKey(), "更新成功");
    }


    @RequestMapping(value = DELETE_FILED + "/delete")
    public
    @ResponseBody
    Message delete(@RequestParam(value = "ids[]") String[] ids) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                Role role = roleService.selectByPrimaryKey(id);
                if (role != null) {
                    if ("0".equals(role.getIsSys())) {
                        return new Message(StatusType.ERROR.getKey(), "系统内置角色,不可删除");
                    }
                    role.setDataStatus(BaseEnum.DATA_STATUS.DELETE.getKey());
                    role.setModifyTime(new Date());
                    role.setModifyBy(getPrincipal().getLoginName());
                    roleService.updateByPrimaryKeySelective(role);
                }
            }
            return new Message(StatusType.SUCCESS.getKey(), "删除成功");
        }
        return new Message(StatusType.WARN.getKey(), "参数错误");
    }


    /**
     * 数据规则选择界面
     *
     * @return
     */
    @RequestMapping(VIEW_FILED + "/dataRule/edit")
    public String authorizationEdit(HttpServletRequest request, Model model) throws ServletRequestBindingException {
        model.addAttribute("id", request.getParameter("id"));
        return "single/role/dataRule";
    }


    /**
     * 数据规则保存
     *
     * @return
     */
    @RequestMapping(INSERT_FILED + "/dataRule/insert")
    public
    @ResponseBody
    Message authorizationInsert(String ids, String roleId, HttpServletRequest request) throws ServletRequestBindingException {
        Assert.notNull(roleId, "参数错误");
        if (StringUtils.isNotBlank(roleId)) {
            //根据roleId 删除之前的数据
            Condition condition = new Condition();
            condition.putEquals("roleId", roleId);
            List<RoleRule> roleRuleList = roleRuleService.selectList(condition, null);
            if (CollectionUtils.isNotEmpty(roleRuleList)) {
                for (RoleRule ur : roleRuleList) {
                    roleRuleService.deleteByPrimaryKey(ur.getId());
                }
            }
        }

        if (StringUtils.isNotBlank(ids)) {
            RoleRule roleRule = null;
            //增加新的角色
            String[] strings = ids.split(",");
            for (String id : strings) {
                roleRule = new RoleRule();
                roleRule.setId(IdUtils64.getInstance().getStringId());
                roleRule.setRuleId(id);
                roleRule.setRoleId(roleId);
                roleRuleService.insert(roleRule);
            }
        }
        Message message = new Message(StatusType.SUCCESS.getKey(), "保存成功");
        return message;
    }


    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping(VIEW_FILED + "/dataRule/list")
    public
    @ResponseBody
    GridVo<Role> authorizationList(String roleId, String name, HttpServletRequest request) throws ServletRequestBindingException {

        Condition params = new Condition();
        if (StringUtils.isNoneBlank(roleId)) {
            params.put("roleId", roleId);
        }

        if (StringUtils.isNoneBlank(name)) {
            params.put("name", name);
        }
        GridVo vo = new GridVo();
        Page<RuleVo> pageResult = ruleService.findRoleRuleList(params, initPageRequest(request, PAGE_NUMBER, PAGE_ROWS));

        return new GridVo(pageResult);
    }


}